// pages/login/regist/index.js
const app = getApp();
const { AskPage } = app._require("common/index");
const formMixin = app._require("mixins/form.mixin.js").default;
const { uploadFile } = app._require("utils/upload.file");
// import { staticUrl } from "./";
import { staticUrl } from "../../../services/config.js";
AskPage({

  /**
   * 页面的初始数据
   */
  name: "regist",
  mixins: [formMixin],
  data: {
    left_checked:true,
    showPicker: false,
    limit_num :0,
    click_checkBox:false,
    columns: [],
    check_box_items:[{"title":"村工作人员","subtitle":"所属村","desc":"请选择所属村"},
                     {"title":"镇工作人员","subtitle":"所属镇","desc":"请选择所属镇"},
                    //  {"title":"第三方组织","subtitle":"单位名称","desc":""}
                    ],
    current_check_box:0,
    parms_town:"",
    tel:"",
    send: true,
    alreadySend: false,
    second: 60,
    header_url:"",
    reverse_url:"",
    positive_url:"",
    reason:"",
    smsCode:"",
    invitationCode:"",
    // villag     
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   console.log(staticUrl);
  },
  onShow(options){
    //  options = {"code":"510115106000","name":"寿安镇","id":"32827"};
    if(options){
      console.log(options);
      this.setData({
        town_name : options.name,
        t_governmentId:options.id
      });
      //获取村
      this.governmentByCode(options.code);
      //获取部门
      this.getDeptByGovId(options.id);
    }
},
  async  getDeptByGovId(govId){
    const response = await this.$_server("user/getDeptByGovId", {
        data: {
          govId: govId,
        },
    });
    let { data } = response;
    if (data.code !== 200) {
        throw data;
    }
    //镇
    let  townList  = data.data;
    let columns = [];
    townList.forEach((ret)=>{
      columns.push(ret.name);
    });
    this.setData({
      "townList":columns,
      "townItems":townList
    })
    console.log(data);
  },
  async governmentByCode(code){
      const response = await this.$_server("user/byCode", {
        params: {
          code: code.length > 0 ? "?code="+code:"?",
        },
    });
    let { data } = response;
    if (data.code !== 200) {
        throw data;
    }
    console.log(data);
    //
    let  villageList  = data.data;
    let columns = [];
    villageList.forEach((ret)=>{
      columns.push(ret.name);
    });
    this.setData({
      "villageList":columns,
      "villageItems":villageList
    })
  },
  clickAddress(){
     console.log("选择");
     wx.navigateTo({
       url: '../../plugins/chose-address/index',
     })
  },
  getInputValue(e){
    // console.log(e.detail.value);
    this.setData({
      limit_num:e.detail.value.length,
      "reason":e.detail.value
    });
  },
  checkBoxAction(){
    this.setData({
      click_checkBox:!this.data.click_checkBox,
    });
  },
  choicekBoxAction(e){
    console.log(e.currentTarget.dataset.index);

    let check_index =  e.currentTarget.dataset.index;
   
    
    this.setData({
      current_check_box : check_index,
      "current_value":"",
      "governmentId":"",
      "departmentId":""
    });
  },
  idImageClick(e){
    console.log(e);
  },
  clickPicker(e){
    let current_check_box = this.data.current_check_box;
    let items_arr = [];
    let error_str = "暂无数据"
    // console.log(items_arr);
    if(current_check_box==0){
      //村
      items_arr = this.data.villageList;
    }else{
      //镇
      items_arr = this.data.townList;
    }
    if(!items_arr || items_arr.length==0){
      // console.log("111");
      wx.showToast({
        title: error_str ,
        icon:"none"
      })
    }else{
      let index = e.currentTarget.dataset.currentindex;
      this.setData({
          "showPicker":true,
      });
    }

  
  },
  phoneInput(e){
    // console.log(e.detail.value);
    this.setData({
      "tel":e.detail.value
    });
  },
  checkPhoneNum: function (phoneNumber) {
    let str = /^1[345789]\d{9}$/
    if (str.test(phoneNumber)) {
      return true
    } else {

      var error_msg = phoneNumber.length>0 ? '手机号不正确':'请输入手机号'; 
      wx.showToast({
        title: error_msg,
        icon: 'none'
      })
      return false
    }
  },
  sendCode(){
    // this.timer();
    let phone = this.data.tel;
    let check_phone = this.checkPhoneNum(phone);
    if(!check_phone){return}  
     console.log("发送验证码");
     this.timer();
     this.sendinvitatitonCode();
  },
  timer: function () {
    this.setData({
      alreadySend: true,
      send: false
    })
    let promise = new Promise((resolve, reject) => {
      let setTimer = setInterval(
        () => {
          console.log(this.data.second);
          this.setData({
            second: this.data.second - 1
          })
          if (this.data.second <= 0) {
            this.setData({
              second: 60,
              alreadySend: false,
              send: true
            })
            resolve(setTimer)
          }
        }, 1000)
    })
    promise.then((setTimer) => {
      clearInterval(setTimer)
    })
  },
  async sendinvitatitonCode(){

    let tel=  this.data.tel;
    const response = await this.$_server("user/invitationSendCode", {
      params: {
        tel: "?tel="+tel
      },
   });

   let { data } = response;
   console.log(data);
   let message  = data.message;
   wx.showToast({
    title: message,
    icon: 'none',
    duration: 2000
  })

  },
  cancel(){
    this.setData({
      "showPicker":false
  });
    // console.log("www");
  },
  confirm(e){
    // console.log(e);
    let village = this.data.villageItems[e.detail.index];
    console.log(village);
    this.setData({
      "current_value":e.detail.value,
      "showPicker":false,
      "governmentId":village.id,
      "departmentId":""
  });
  },
  conTownfirm(e){
    // console.log(e);
    let town = this.data.townItems[e.detail.index];
    console.log(town);
    let governmentId = this.data.t_governmentId || "";
    this.setData({
      "current_value":e.detail.value,
      "showPicker":false,
      "departmentId":town.id,
      "governmentId":governmentId
  });
  },
  clickUserImage(e){

    let key =  e.currentTarget.dataset.key;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res)=> {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFiles = res.tempFiles;
        console.log(tempFiles);
        this.upload(tempFiles,key);

      }
    })      
  },
  getCredentials() {
    return new Promise(async (resolve, reject) => {
        const response = await this.$_server("cosAuth");
        let { data } = response;
        if (data.code !== 200) {
            reject(data);
        }
        resolve(data.data);
    });
  },
  async upload(files,key) {
    wx.showLoading({
        title: "上传中...",
        mask: true,
    });
    try {
        const nowTime = new Date();
        const uploadList = files.map(file => ({
            dir: this.data.uploadImageProps.dir + nowTime.format("yyyy/MM/dd") + "/",
            filePath: file.path || "",
            size: file.size,
            _id: "choose",
        }));
        let url = "";
        console.log("getCredentials",uploadList);
        const _response = await uploadFile(uploadList, {
            limit: 10 * 1024 * 1024,
            timeout: 60*1000,
            action: this.data.actionUrl,
            initAuth: this.getCredentials.bind(this),
            onReady: files => {
                this.triggerEvent("update", {
                    type: "upload",
                    list: files,
                    item: null,
                });
            },
            beforeUpload: (curFile, files) => {
                this.triggerEvent("update", {
                    type: "upload",
                    list: files,
                    item: curFile,
                });
            },
            afterUpload: (curFile, files, errors) => {
                if (errors && errors.length > 0) {
                    wx.askShowToastEx({
                        icon: "none",
                        title: "上传文件只能在" + 10 + "M以内",
                    });
                }
                url = curFile;
                this.triggerEvent("update", {
                    type: "upload",
                    list: files,
                    item: curFile,
                });
            },
        });

        // console.log(_response);

        wx.hideLoading();
        // console.log("上传成功 key="+key);
        console.log(url.fileName);
        wx.showToast({
          title: "上传成功",
          icon: "none",
      }); 


        if(key=="header"){
            this.setData({
              "header_url" :  staticUrl+"/" +url.fileName
            });
           
        }else if(key=="reverse"){
          this.setData({
            "reverse_url" : staticUrl+"/" +url.fileName
          });
         
        }else{
          this.setData({
            "positive_url" :staticUrl+"/" + url.fileName
          })
         
        }
        // this.updateUser(url.fileName);
        // this.$emit("setModel", { value: url.src });
    } catch (error) {
        wx.hideLoading();
        console.log(error);
    }
  },
  registForm:function(data){
 
    let { town, password,name ,phone,code,otherCode} = data.detail.value;
      

    let positive_url = this.data.positive_url;
    positive_url = positive_url.replace(staticUrl,"");

  
    let reverse_url = this.data.reverse_url;
    reverse_url = reverse_url.replace(staticUrl,"");
 

    // let phone = this.data.tel;
    let check_phone = this.checkPhoneNum(phone);
    if(!check_phone){return}  
    
    let res = this.validateFiled([
      [name, { required: "请输入姓名!" }],
      [code, { required: "请输入验证码!" }],
      [password, { required: "请输入登录密码!" }],
      [otherCode, { required:"请输入邀请码!"}],
      [this.data.click_checkBox,{isTrue:"请阅读并同意声明"}],
  ]);
   
  
  if (!res.result) {
      wx.showToast({
          title: res.msg,
          icon: "none",
      });
      return false;
  }
  console.log(name);
  this.registerAction(data);

  },
  async registerAction(e){


    let { town,company ,password,name ,phone,code,otherCode} = e.detail.value;
        
    let current_check_box = this.data.current_check_box;
    let userType = 1;
    if(current_check_box==2){
      //村
      userType = 2;
    }
    if(userType==1){
      //镇干部
      let governmentId = this.data.governmentId||"";
      if(governmentId.length==0){
        let t_governmentId = this.data.t_governmentId||"";
        this.setData({
          governmentId:t_governmentId
        })
      }
    }

    const response = await this.$_server("user/register", {
      data: {
        // cardBack: this.data.reverse_url,
        // cardFront:this.data.positive_url,
        headPortrait:this.data.header_url,
        company:company,
        applyReason:this.data.reason,
        tel:phone,
        username:phone,
        password:password,
        name:name,
        smsCode:code,
        invitationCode:otherCode,
        userType:userType,
        governmentIds:[this.data.governmentId],
        departmentId:this.data.departmentId
      },
  });
  
   let { data } = response;
  //  console.log(data);

   wx.showToast({
     title: data.message,
     icon:"none"
   })


    if(data.code==200){
      wx.navigateBack({
        delta: 0,
      })
    }
  }



})

